package com.lsk.task;

import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.lsk.util.AlipayUtil;
import com.lsk.util.UtilUUID;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理提现
 */
public class WithdrawTask implements Runnable {
    @Override
    public void run() {
        List<Record> list = Db.find("select a.*,b.type,b.alipayId,b.alipayAccount,b.realName" +
                " from withdrawLog a left join yx_member b on a.memberId=b.id where a.state=0");
        for (Record record:list){
            record.getStr("money");
            Map<String, String> map = new HashMap<>();
            /*支付宝转账*/
            if ("3".equals(record.getStr("type")) || "5".equals(record.getStr("type"))) {//支付宝会员具有支付宝userId

                System.out.println("通过userId向个人转账");

                map.put("payee_type", "ALIPAY_USERID");
                map.put("payee_account", record.getStr("alipayId"));
            } else {
                System.out.println("通过真实姓名，支付宝保定账户向个人转账");
                map.put("payee_type", "ALIPAY_LOGONID");
                map.put("payee_account", record.getStr("alipayAccount"));
                //参数
                map.put("payee_real_name", record.getStr("realName"));
            }
            map.put("amount", record.getStr("money"));
            map.put("remark", "提现转账");
            map.put("cardId", UtilUUID.getOrderIdByUUId());
            System.out.println("支付参数:" + map);
            AlipayFundTransToaccountTransferResponse response = null;//返回结果
            try {
                response = AlipayUtil.pay(map);

                System.out.println(response.getBody());

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (response != null) {
                if (response.isSuccess()) {
                    /**添加返利信息*/
                    Db.update("withdrawLog","id",new Record().set("id",record.getStr("memberId")).set("state","1"));
                } else {
                    Db.update("withdrawLog","id",new Record().set("id",record.getStr("memberId"))
                            .set("state","2").set("errCodeDes",response.getSubMsg()).set("response.getSubCode()",response.getSubCode()));
                }
                System.out.println("支付结果:" + response.getMsg());
            } else {
                Db.update("withdrawLog","id",new Record().set("id",record.getStr("memberId")).set("state","2"));
            }
        }
    }
}
